#!/usr/local/bin python3
# coding=utf-8

"""
钉钉定时群提醒机器人
author：duicym
date：2017-12-18 16:17:20

"""

import sys
from urllib import parse, request
import json
import time


# 推送机器人类
class DingBot(object):
    """ dingTalk机器人实例 """
    webHook = ''

    def __init__(self, web_hook):
        super(DingBot, self).__init__()
        self.webHook = web_hook

    # text类型
    def sentText(self, content, is_at_all=False, at_mobiles=[]):
        data = {"msgtype": "text", "text": {"content": content}, "at": {"atMobiles": at_mobiles, "isAtAll": is_at_all}}
        return self.post(data)

    # actionCard 类型
    def setActionCard(self, actionCard):
        data = actionCard.getData()
        return self.post(data)

    def post(self, data):
        post_data = json.dumps(data).encode(encoding='utf-8')
        print(post_data)
        req = request.Request(self.webHook, post_data)

        req.add_header('Content-Type', 'application/json')
        content = request.urlopen(req).read()
        return content


# ActionCard类
class ActionCard(object):
    """
    ActionCard 消息结构字段
    整体跳转 需要配置 singleTitle singleURL 不需要配置 btns
    独立跳转 需要配置 btns 不需要配置 singleTitle singleURL
    """
    title = ''
    text = ''
    hideAvatar = ''  # 0-正常发消息者头像,1-隐藏发消息者头像
    btnOrientation = ''  # 0-按钮竖直排列，1-按钮横向排列
    btns = []
    singleTitle = ''
    singleURL = ''

    def __init__(self, args=""):
        super(ActionCard, self).__init__()
        self.args = args

    def putBtn(self, title, actionURL):
        self.btns.append({"title": title, "actionURL": actionURL})

    def getData(self):
        data = {"actionCard": {"title": self.title, "text": self.text, "hideAvatar": self.hideAvatar,
                               "btnOrientation": self.btnOrientation, "btns": self.btns,
                               "singleTitle": self.singleTitle,
                               "singleURL": self.singleURL},
                "msgtype": "actionCard"}
        return data